package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealDao;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Override
    public void add(Setmeal setmeal, List<Integer> checkgroupIds) {
        // 将新增套餐保存到t_setmeal表中
        setmealDao.add(setmeal);

        // 获取新增套餐的id
        Integer setmealId = setmeal.getId();

        // 保存套餐id和关联的检查组id到t_setmeal_checkgroup表中
        checkgroupIds.forEach(checkGroupId -> {
            setmealDao.addSetmealAndCheckGroup(setmealId, checkGroupId);
        });
    }

    @Override
    public void update(Setmeal setmeal, List<Integer> checkGroupIds) {
        // 将套餐对象保存到t_setmeal表中
        setmealDao.update(setmeal);

        // 查询新增套餐对象的id
        Integer setmealId = setmeal.getId();

        // 根据套餐id删除t_setmeal_checkgroup表中的记录
        setmealDao.deleteSetmealAndCheckGroupBySetmealId(setmealId);

        // 保存套餐id和关联的检查组id到t_setmeal_checkgroup表中
        checkGroupIds.forEach(checkGroupId -> {
            setmealDao.addSetmealAndCheckGroup(setmealId, checkGroupId);
        });
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findPage(queryPageBean);
        return new PageResult(page.getTotal(), page.getResult());
    }
}
